/******************************************************************************
 * This file is part of ZEMB.
 *
 * ZEMB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ZEMB is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ZEMB.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: zemb
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://gitee.com/newgolo/embedme.git
 * Copyright 2014~2022 @ ShenZhen ,China
*******************************************************************************/
#ifndef __MEM_UTIL_H__
#define __MEM_UTIL_H__

#include "zemb/BaseType.h"
#include <iostream>
#include <vector>

/**
 * @file MemUtil.h 
 * @brief 内存工具
 */
namespace zemb{

/**
 * @class MemPool
 * @brief 内存池
 */
class MemPool{
DECL_CLASSNAME(MemPool)
public:
    MemPool();
    ~MemPool();
    bool init(int blockNum,int blockSize,void* memStart=NULL);/* 如果指定了memStart则在memStart内存地址处创建内存池 */
    void* getMemory(const std::string& memoryName,int memorySize);
    bool putMemory(const std::string&  memoryName);
    void showMemory();
private:
    struct MemBlock{
        bool m_isUsed{false};
        void* m_address{NULL};
        std::string m_name{""};
    };
    void* m_memory{NULL};
    int m_blockNum{0};
    int m_blockSize{0};
    int m_poolSize{0};
    std::vector<std::unique_ptr<MemBlock>> m_memBlocks;
};


/**
 *  @class  MemShared
 *  @brief  共享内存类(可以多进程共享)
 */
class MemShared{
DECL_CLASSNAME(MemShared)
public:
	enum TYPE_E{
	TYPE_SHM=0,
	TYPE_FILE
	};
public:
    MemShared(int type);
    virtual ~MemShared();
    bool open(std::string name, int size=-1);
    bool close();
	void* attach();
    int detach();
	int size();
	void* address();
   
private:
	int m_fd{-1};
    int m_type{TYPE_SHM};
    int m_size{0};
    void* m_address{NULL};
	std::string m_name{""};
};
}
#endif
